package com.boruan.shengtangfeng.core.service.impl;

import java.util.Date;
import java.util.List;

import com.boruan.shengtangfeng.core.entity.SystemUserRole;
import com.boruan.shengtangfeng.core.utils.GlobalReponse;
import com.boruan.shengtangfeng.core.dao.IRoleDao;
import com.boruan.shengtangfeng.core.entity.Role;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.boruan.shengtangfeng.core.service.IRoleService;

/**
 * 
 * @author liuguangqiang
 * @date 2016年8月10日 上午9:36:16
 */
@Service
@Transactional(readOnly = true)
public class RoleService implements IRoleService{

	@Autowired
	private IRoleDao roleDao;
	@Autowired
	private SQLManager sqlManager;

	@Override
	public List<Role> findByUserId(Long userId) {
		Assert.notNull(userId,"用户Id不能为空");
		return roleDao.findByUserId(userId);
	}
	
	
	
	@Override
	public void pageQuery(PageQuery<Role> pageQuery, Role role) {
		pageQuery.setParas(role);
		roleDao.pageQuery(pageQuery);
	}
	
	@Override
	public Role findById(Long id) {
		return roleDao.unique(id);
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Role role) {
		if (role.getId()!=null) {
			roleDao.updateTemplateById(role);
		}else{
			KeyHolder kh=roleDao.insertReturnKey(role);
			role.setId(kh.getLong());
		}
	}

	@Override
	public List<Role> findAll() {
		Role search=new Role();
		search.setIsDeleted(false);
		return roleDao.template(search);
	}
	
	@Override
	public Role findSystemRoleByNameAndIsSystemRole(String name,
			boolean isSystemRole) {
		return roleDao.findSystemRoleByNameAndIsSystemRole(name, isSystemRole);
	}
	
	@Override
	public List<Role> findSysRole() {
		return roleDao.findSysRole();
	}

	/**
	 * 删除角色，验证该角色下是否存在用户
	 * @param id
	 * @param userId
	 * @return
	 */
	@Override
	public GlobalReponse delRole(Long id, Long userId) {

		//判断是否存在角色
		int count = sqlManager.execute(new SQLReady("select * from system_user_role where role_id = ?", id), SystemUserRole.class).size();

		if (count > 0) {
			return GlobalReponse.fail("当前角色下存在用户，请删除或者重新赋予角色后再进行操作");
		}

		//更改role表
		sqlManager.executeUpdate(new SQLReady("update role set is_deleted = 1, update_by = ?, update_time = ? where id = ?", userId, new Date(), id));

		return GlobalReponse.success();
	}
}
